#!/usr/bin/env python

#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

# when a user clicks a link to leave search, this script logs it

from dbinter import *
import cgi
import re
from util import cui

def userMessage():
	print """
	Content-type: text/html\n\n
	<html><head><title>Invalid URL</title></head><body>
	URL Error - Please report this error to the administrator's email.<br>
	Be sure to include a copy of the URL in your email. Thank you.
	</body></html>
	"""

# record the user info in the database
def recordUser():
	params = cgi.FieldStorage()
	try:
		# catch bad input
		search = ''
		if params.has_key('s'):
			search = params['s'].value
		record = params['i'].value
		urlloc = params['u'].value
	except:
		# catch all for invalid URL - will make this better later
		userMessage()
		return

	if len(urlloc) < 1:	# the checking here could be improved
		# no url provided
		userMessage()
		return

	# parse the terms
	terms = parseTerms(search)

	# escape mysql chars
	esc = escape_mysql()
	terms = esc.escape(terms)

	# put the data in the db
	storeData(terms,record)

	# redirect the user
	redirect(urlloc)

def storeData(terms, recID):
	db = oai_db()
	db.connect()
	insert = """
		INSERT INTO harvestUserMod (
		recHash, keywordSearch )
		VALUES ('%s','%s');
		""" % (cui(recID), cui(terms))
	db.query(insert)
	db.disconnect()

def parseTerms(termStr):
	termStr = ' ' + termStr + ' ' # padding
	fpar = re.compile('\w+:(".+?"|\w+)')
	xpar = re.compile('-\w+|-".+?"')
	qpar = re.compile('"')
	# remove excluded words
	termStr = xpar.sub(' ', termStr)
	# remove field names
	termStr = fpar.sub(' ', termStr)
	# remove quotes around phrases
	termStr = qpar.sub(' ', termStr)
	return termStr

# redirect the user to their page
def redirect(url):
	sAmp = re.compile(r'%26amp%3B',re.IGNORECASE)
	url = sAmp.sub('&', url)
	print "Location: %s\n\n" % url
	print """
Content-type: text:/html\n\n
<html><head><title>Redirect</title>
</head><body>
If you were not redirected automatically, please follow this link:<br>
<a href='%s'>%s</a>
</body></html>
	""" % (url,url)

# begin execution
def url():
	recordUser()

if __name__ == '__main__' or __name__ == 'url':
	url()


# eof

